package cn.hznc.controller.service.sharefile;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.configuration.SystemInit;
import cn.hznc.constant.CommonConstant;
import cn.hznc.domain.entity.ConfigurationEntity;
import cn.hznc.domain.entity.MachineToolProgramEntity;
import cn.hznc.domain.response.PageResult;
import cn.hznc.mapper.ConfigurationMapper;
import cn.hznc.mapper.MachineToolProgramMapper;
import cn.hznc.repository.MachineToolProgramRepository;
import cn.hznc.repository.WarehouseRespository;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author：Administrator
 * @Date：2023/9/14 9:59
 */
@Service
public class ShareFileService {

    @Resource
    private ConfigurationMapper configurationMapper;

    @Resource
    private MachineToolProgramMapper machineToolProgramMapper;

    @Resource
    private MachineToolProgramRepository machineToolProgramRepository;

    @Resource
    private WarehouseRespository warehouseRespository;

    private static final ConcurrentHashMap<Integer, List<Integer>> groupMap = new ConcurrentHashMap<>();
    private static final List<Integer> group1List = new ArrayList<>();
    private static final List<Integer> group2List = new ArrayList<>();
    private static final List<Integer> group3List = new ArrayList<>();

    static {
        group1List.add(30);
        group1List.add(31);
        group1List.add(32);
        group1List.add(33);

        group2List.add(36);
        group2List.add(37);
        group2List.add(38);
        group2List.add(39);

        group3List.add(9);
        group3List.add(26);
        group3List.add(27);
        group3List.add(28);
        group3List.add(29);

        groupMap.put(1 , group1List);
        groupMap.put(2 , group2List);
        groupMap.put(3 , group3List);
    }

    private void fileReadRecursiveRemoteExample() {
        String folderPath = "/data"; // 指定要读取的文件夹路径
        String username = "your_username"; // 替换为您的用户名
        String password = "your_password"; // 替换为您的密码
        String serverUrl = "http://192.168.202.53"; // 替换为远程服务器的URL
        try {
            URL url = new URL(serverUrl + folderPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 设置连接超时时间（毫秒）
            connection.setInstanceFollowRedirects(false); // 禁止自动跟随重定向
            connection.setDoOutput(true); // 允许向服务器输出内容
            connection.setRequestProperty("Authorization", "Basic " + java.util.Base64.getEncoder().encodeToString((username + ":" + password).getBytes())); // 设置身份验证信息头
            int responseCode = connection.getResponseCode(); // 获取响应码
            if (responseCode == 200) { // 如果响应码为200，表示请求成功
                try (InputStream inputStream = connection.getInputStream()) {
                    Stream<Path> paths = Files.walk(Paths.get(folderPath));
                    paths.filter(Files::isRegularFile) // 过滤出所有普通文件
                            .forEach(System.out::println); // 输出每个文件的路径
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    connection.disconnect(); // 断开连接
                }
            } else { // 如果响应码不为200，表示请求失败
                System.out.println("Failed to access the file, response code: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void insertShareFile() {
        List<MachineToolProgramEntity> insertList = new ArrayList<>();
        try {
            Object o = SystemInit.configurationMap.get("shareFile");
            List<String> shareFiles= new ArrayList<>();
            if(ObjectUtil.isNotNull(o)){
                shareFiles = JSONArray.parseArray(o.toString() , String.class);
            }
            if(CollectionUtil.isNotEmpty(shareFiles)){
                for (String shareFile : shareFiles) {
                    SmbFile smbFile = new SmbFile(shareFile);
                    smbFile.connect(); //尝试连接
                    int i = 3;
                    List<String> fileNames = new ArrayList<>();
                    recursion(smbFile , fileNames , i , 0);
                    //TO DO 处理路径
                    fileNames.forEach(s -> {
                        String[] split = s.split("\\/");
                        MachineToolProgramEntity machineToolProgramEntity = new MachineToolProgramEntity();
                        machineToolProgramEntity.setPartno(split[7]);
                        String program = split[8];
                        if(program.equals("新建文件夹")){
                            return;
                        }
                        machineToolProgramEntity.setProgram(program);
                        machineToolProgramEntity.setMachineToolIds(JSONArray.toJSONString(parseProgram(program)));
                        //System.out.println("物料编码 ：" + split[7] + "|" +"对应程序 ：" + split[8]);
                        insertList.add(machineToolProgramEntity);
                    });
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(CollectionUtil.isNotEmpty(insertList)){
            machineToolProgramMapper.delete(new QueryWrapper<>());
            machineToolProgramMapper.insertBatchSomeColumn(insertList);
        }
    }

    private List<Integer> parseProgram(String program) {
        if(program.endsWith("C22") || program.endsWith("c22")){
            //科德
            return groupMap.get(1);
        }else if(program.endsWith("KD") || program.endsWith("kd")){
            //海德汉
            return groupMap.get(2);
        }else if(program.endsWith(".WPD") || program.endsWith(".wpd")){
            return groupMap.get(3);
        }
        return new ArrayList<>();
    }

    private void recursion(SmbFile dir , List<String> fileNames , int i , int j) throws SmbException {
        ///fileNames.add(dir.getPath())
        //System.out.println(dir.getPath());
        //调用listFiles方法对目录进行遍历
        boolean directory = dir.isDirectory();
        SmbFile[] filearr = dir.listFiles();
        for (SmbFile file : filearr){
            if (file.isDirectory()){
                if(i == j){
                    fileNames.add(file.getPath());
                    continue;
                }
                j++;
                recursion(file,fileNames , i , j);//判断如果是文件夹就继续调用遍历目录下内容的方法，形成递归
                j--;
            }
        }
    }
    public List<String> queryMachineToolProgram(String partno) {
        QueryWrapper<MachineToolProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("partno" , partno);
        List<MachineToolProgramEntity> machineToolProgramEntities = machineToolProgramMapper.selectList(wrapper);
        return CollectionUtil.isNotEmpty(machineToolProgramEntities)?
                machineToolProgramEntities.stream().map(MachineToolProgramEntity::getProgram).collect(Collectors.toList()) : new ArrayList<>();
    }

    public Object queryMachineToolProgramGroup(String partno , Integer pageNum , Integer pageSize) {
        PageHelper.startPage(pageNum , pageSize);
        QueryWrapper<MachineToolProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.like("partno" , partno);
        PageInfo<MachineToolProgramEntity> machineToolProgramEntityPageInfo = new PageInfo<>(machineToolProgramMapper.selectList(wrapper));
        List<MachineToolProgramEntity> machineToolProgramEntities = machineToolProgramMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(machineToolProgramEntityPageInfo.getList())){
            machineToolProgramEntityPageInfo.getList().forEach(machineToolProgramEntity -> {
                if(!machineToolProgramEntity.getMachineToolIds().equals("[]")){
                    List<Integer> ids = JSONArray.parseArray(machineToolProgramEntity.getMachineToolIds(), Integer.class);
                    machineToolProgramEntity.setMachineToolName(ids.stream().map(integer -> warehouseRespository.getNameByWarehouseId(integer)).collect(Collectors.toList()));
                }
                machineToolProgramEntity.setCount(machineToolProgramRepository.selectCount(machineToolProgramEntity.getPartno()));
            });
        }
        return new PageResult<>(machineToolProgramEntityPageInfo.getList() , machineToolProgramEntityPageInfo.getTotal());
    }

    public List<String> queryMachineToolProgramGroupReload(String partno) {
        QueryWrapper<MachineToolProgramEntity> wrapper = new QueryWrapper<>();
        wrapper.like("partno" , partno);
        //PageInfo<MachineToolProgramEntity> machineToolProgramEntityPageInfo = new PageInfo<>(machineToolProgramMapper.selectList(wrapper));
        List<MachineToolProgramEntity> machineToolProgramEntities = machineToolProgramMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(machineToolProgramEntities)){
            machineToolProgramEntities.forEach(machineToolProgramEntity -> {
                if(!machineToolProgramEntity.getMachineToolIds().equals("[]")){
                    List<Integer> ids = JSONArray.parseArray(machineToolProgramEntity.getMachineToolIds(), Integer.class);
                    machineToolProgramEntity.setMachineToolName(ids.stream().map(integer -> warehouseRespository.getNameByWarehouseId(integer)).collect(Collectors.toList()));
                }
                machineToolProgramEntity.setCount(machineToolProgramRepository.selectCount(machineToolProgramEntity.getPartno()));
            });
        }
        List<List<String>> machineToolNamesList = machineToolProgramEntities
                .stream()
                .filter(machineToolProgramEntity -> CollectionUtil.isNotEmpty(machineToolProgramEntity.getMachineToolName()))
                .map(MachineToolProgramEntity::getMachineToolName)
                .collect(Collectors.toList());
        List<String> resultList = new ArrayList<>();
        machineToolNamesList.forEach(resultList::addAll);
        return ObjectUtil.isNotNull(resultList)? resultList.stream().distinct().collect(Collectors.toList()) : resultList;
    }
}
